/**
 * 测试1387物品使用功能 - 验证星级类型随机选择逻辑
 * 测试新的star_level随机选择机制
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    }
};

class StarLevelTester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
        this.selectedCharacter = null;
        this.testResults = [];
    }

    async runTest() {
        console.log('🚀 开始测试1387物品使用 - 星级类型随机选择逻辑...\n');
        console.log('测试目标：验证根据star_level随机选择基础副将的功能\n');

        try {
            // 1. HTTP登录
            await this.testHttpLogin();

            // 2. 建立WebSocket连接
            await this.testWebSocketConnection();

            // 3. 查询角色列表
            await this.testQueryCharacters();

            // 4. 选择角色
            await this.testSelectCharacter();

            // 5. 测试不同物品的星级类型生成
            await this.testStarLevelGeneration();

            // 6. 断开连接
            await this.testDisconnect();

            // 输出测试结果
            this.printTestResults();

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
            this.addTestResult('整体测试', false, error.message);
        }
    }

    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录测试...');

        try {
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;
                console.log(`✅ 登录成功: userId=${this.userId}`);
                this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }
        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            this.addTestResult('HTTP登录', false, error.message);
            throw error;
        }
    }

    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接测试...');

        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');
                    this.addTestResult('WebSocket连接', true, '连接建立成功');
                    this.setupMessageHandler();
                    await this.delay(500);
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    this.addTestResult('WebSocket连接', false, error.message);
                    reject(error);
                });

                setTimeout(() => {
                    if (this.ws.readyState === WebSocket.CONNECTING) {
                        this.ws.close();
                        reject(new Error('连接超时'));
                    }
                }, 10000);

            } catch (error) {
                reject(error);
            }
        });
    }

    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));
                this.handleWebSocketResponse(message);
            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    handleWebSocketResponse(message) {
        const { act_id, code, roleList, roleCount, data, msg } = message;

        switch (act_id) {
            case 3: // 查询角色列表响应
                if (roleList && Array.isArray(roleList)) {
                    this.characters = roleList;
                    console.log(`📋 获取到${roleCount || roleList.length}个角色`);
                }
                break;

            case 4: // 角色选择响应
                if (code === 0) {
                    console.log('🎯 角色选择成功');
                }
                break;

            case 1387: // 物品使用响应
                console.log(`🎖️ 物品使用结果:`, JSON.stringify(message, null, 2));
                break;

            default:
                break;
        }
    }

    async testQueryCharacters() {
        console.log('\n📋 步骤3: 查询角色列表...');

        return new Promise(async (resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('查询角色列表', false, 'WebSocket未连接');
                resolve();
                return;
            }

            await this.delay(1000);

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.roleList && Array.isArray(message.roleList)) {
                            this.characters = message.roleList;
                            console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
                            this.addTestResult('查询角色列表', true, `获取${this.characters.length}个角色`);
                        } else {
                            this.characters = [];
                            console.log('✅ 查询成功，暂无角色');
                            this.addTestResult('查询角色列表', true, '获取0个角色');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('查询角色列表', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            this.ws.send(JSON.stringify({
                c: 3,
                d: null
            }));

            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('查询角色列表', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testSelectCharacter() {
        console.log('\n🎯 步骤4: 选择角色...');

        if (this.characters.length === 0) {
            console.log('⚠️ 没有可选择的角色');
            this.addTestResult('选择角色', false, '没有可用角色');
            return;
        }

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('选择角色', false, 'WebSocket未连接');
                resolve();
                return;
            }

            const targetCharacter = this.characters[0];

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 4) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.code === 0) {
                            this.selectedCharacter = targetCharacter;
                            console.log(`✅ 角色选择成功: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
                            this.addTestResult('选择角色', true, `选择角色: ${targetCharacter.name}`);

                            setTimeout(() => {
                                resolve();
                            }, 2000);
                        } else {
                            console.log(`❌ 角色选择失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('选择角色', false, message.msg || '选择失败');
                            resolve();
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('选择角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            this.ws.send(JSON.stringify({
                c: 4,
                d: {
                    characterId: targetCharacter.id
                }
            }));

            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('选择角色', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testStarLevelGeneration() {
        console.log('\n🎖️ 步骤5: 测试星级类型生成逻辑...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('星级类型测试', false, 'WebSocket未连接');
            return;
        }

        // 测试物品列表
        const testItems = [
            { id: 62, name: "将军令", expectedStarLevel: 3 }, // 100%英才
            { id: 141, name: "将军令(绑)", expectedStarLevel: 3 }, // 100%英才
            { id: 63, name: "大将军令", expectedStarLevel: "random" }, // 随机
            { id: 331, name: "大将军令(绑)", expectedStarLevel: "random" }, // 随机
        ];

        for (const item of testItems) {
            await this.testSingleItem(item);
            await this.delay(1000); // 等待1秒再测试下一个
        }
    }

    async testSingleItem(item) {
        console.log(`\n📦 测试物品: ${item.name} (ID: ${item.id})`);

        return new Promise((resolve) => {
            let responseReceived = false;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1387) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log(`✅ ${item.name}使用成功`);

                            // 验证返回的数据结构
                            if (message.data && message.data.starLevel !== undefined) {
                                const starLevel = message.data.starLevel;
                                const typeName = message.data.typeName;

                                console.log(`   生成的星级类型: ${starLevel} (${typeName})`);

                                // 验证将军令应该100%生成英才
                                if (item.id === 62 || item.id === 141) {
                                    if (starLevel === 3) {
                                        console.log(`   ✅ 将军令正确生成英才类型`);
                                        this.addTestResult(`${item.name}类型验证`, true, `正确生成英才类型`);
                                    } else {
                                        console.log(`   ❌ 将军令应该生成英才类型，但生成了${typeName}`);
                                        this.addTestResult(`${item.name}类型验证`, false, `应该生成英才但生成了${typeName}`);
                                    }
                                } else {
                                    // 大将军令随机生成
                                    console.log(`   ✅ 大将军令随机生成${typeName}类型`);
                                    this.addTestResult(`${item.name}类型验证`, true, `随机生成${typeName}类型`);
                                }

                                // 验证副将数据
                                if (message.data.deputy) {
                                    console.log(`   生成的副将: ${message.data.deputy.name} (ID: ${message.data.deputy.deputy_id})`);
                                    console.log(`   副将属性: AP=${message.data.deputy.ap}, HP=${message.data.deputy.hp}, MP=${message.data.deputy.mp}`);
                                }
                            } else {
                                console.log(`   ❌ 返回数据缺少starLevel字段`);
                                this.addTestResult(`${item.name}数据结构验证`, false, '缺少starLevel字段');
                            }
                        } else {
                            console.log(`❌ ${item.name}使用失败: ${message.msg || '未知错误'}`);
                            this.addTestResult(`${item.name}使用测试`, false, message.msg || '使用失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error(`❌ ${item.name}响应解析失败:`, error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult(`${item.name}响应解析`, false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送物品使用请求
            const requestData = {
                c: 1387,
                d: { gid: item.id }
            };

            console.log(`📤 发送${item.name}使用请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult(`${item.name}使用测试`, false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    async testDisconnect() {
        console.log('\n🔌 步骤6: 断开WebSocket连接...');
        if (this.ws) {
            this.ws.close();
        }
        this.addTestResult('断开连接', true, '连接已断开');
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(60));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(60));
        console.log(`总计: ${successCount}/${totalCount} 项测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！星级类型随机选择逻辑工作正常！');
        } else {
            console.log('⚠️  部分测试失败，请检查日志');
        }

        console.log('\n📋 测试总结:');
        console.log('- 验证了将军令100%生成英才类型');
        console.log('- 验证了大将军令随机生成不同类型');
        console.log('- 验证了根据star_level随机选择基础副将的逻辑');
        console.log('- 验证了返回数据结构的完整性');
    }

    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, (res) => {
                let body = '';

                res.on('data', (chunk) => {
                    body += chunk;
                });

                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => {
                reject(error);
            });

            if (data) {
                req.write(JSON.stringify(data));
            }

            req.end();
        });
    }

    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 运行测试
async function main() {
    const tester = new StarLevelTester();
    await tester.runTest();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = StarLevelTester;
